/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package engine.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import landapplication.LandApplication;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 */
public class Request {

    private static Request INSTACE;
    private final String USER_AGENT = "Mozilla/5.0";
    private final String TARGET_URL = "http://localhost:8080/land";

    /**
     *
     * @return
     */
    public static Request getInstance() {

        if (INSTACE == null) {

            INSTACE = new Request();
        }

        return INSTACE;
    }

    /**
     *
     * @param userName
     * @param password
     */
    public void sendAuthenticationResquest(String userName, String password) {
        try {
            String url = TARGET_URL + "?userName=" + userName + "&password=" + password;

            System.out.println("Target URL is " + url);

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setRequestProperty("User-Agent", USER_AGENT);

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                response.append(inputLine);
            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(response.toString())));
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

//            File fXmlFile = new File("/Users/mkyong/staff.xml");
//            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//            String encoded = java.net.URLEncoder.encode(response.toString(), "UTF-8");
//            Document doc = dBuilder.parse(encoded);

            in.close();

            //print result
            System.out.println(response.toString());
        } catch (MalformedURLException ex) {
            Logger.getLogger(LandApplication.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LandApplication.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void stringToDom(String xmlSource)
            throws SAXException, ParserConfigurationException, IOException {
        // Parse the given input
//        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//        DocumentBuilder builder = factory.newDocumentBuilder();
//        Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
//
//        // Write the parsed document to an xml file
//        TransformerFactory transformerFactory = TransformerFactory.newInstance();
//        TransformerFactory transformer = transformerFactory.newTransformer();
//        DOMSource source = new DOMSource(doc);
//
//        StreamResult result = new StreamResult(new File("my-file.xml"));
//        transformer.transform(source, result);
    }

}
